﻿using System;
using System.Threading.Tasks;
using MassTransit.Courier;
using MassTransitDemo.ProcessingService.Models;
using MassTransitDemo.Shared;

namespace MassTransitDemo.ProcessingService.Activities
{
    public class ValidateActivity : IExecuteActivity<IValidateArguments>
    {
        public async Task<ExecutionResult> Execute(ExecuteContext<IValidateArguments> context)
        {
            try
            {
                var address = context.Arguments.Address;
                if (address == 0)
                {
                    await context.Publish<IRequestRejected>(new
                    {
                        context.Arguments.RequestId,
                        context.TrackingNumber,
                        Timestamp = DateTime.UtcNow,
                        ReasonCode = 500,
                        ReasonText = "The address was not specified",
                    });

                    return context.Terminate();
                }

                if (address == 1)
                {
                    await context.Publish<IRequestRejected>(new
                    {
                        context.Arguments.RequestId,
                        context.TrackingNumber,
                        Timestamp = DateTime.UtcNow,
                        ReasonCode = 403,
                        ReasonText = "The host specified is forbidden: " + address,
                    });

                    return context.Terminate();
                }

                Console.WriteLine($"Address:{address}");

                return context.Completed();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
    }
}
